<template>
  <div class="mainsu">
    <div class="main_spac1">
      <div class="main_white padding10 paddingBottom20">
        <div class="mainor_form">
          <div class="mainor_te">
            <router-link to="/marketing/coupon/add">
              <el-button type="primary">新增优惠券</el-button></router-link
            >
          </div>
          <el-form
            :inline="true"
            :model="form"
            class="demo-form-inline"
            ref="userListFrom"
            label-width="70px"
          >
            <el-form-item label="券名称" prop="title">
              <el-input
                v-model.trim="form.title"
                placeholder="券名称"
                clearable
                class="wid220"
              ></el-input>
            </el-form-item>
            <el-form-item label="类型" prop="type">
              <el-select
                v-model.trim="form.type"
                placeholder="类型"
                class="wid220"
              >
                <el-option label="所有" :value="parseInt(0)"></el-option>
                <el-option
                  v-for="(item, index) in type_list"
                  :key="index"
                  :label="item"
                  :value="parseInt(index)"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="活动状态" prop="status">
              <el-select
                v-model.trim="form.status"
                placeholder="活动状态"
                class="wid220"
              >
                <el-option label="所有" :value="parseInt(0)"></el-option>
                <el-option
                  v-for="(item, index) in status_list"
                  :key="index"
                  :label="item"
                  :value="parseInt(index) + 1"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button
                class="reset marginLeft10"
                type="primary"
                @click="reset(1)"
                >重置</el-button
              >
              <el-button
                type="primary"
                @click="getArticleList(1)"
                :loading="listLoading"
                >搜索</el-button
              >
            </el-form-item>
          </el-form>
        </div>
        <div class="main_table marginTop10" style="min-height: 550px">
          <el-table
            ref="multipleTable"
            v-loading="listLoading"
            :data="list"
            element-loading-text="加载中"
            fit
            border
            highlight-current-row
            :header-cell-class-name="this.$verticaline"
          >
            <el-table-column
              label="优惠券名称"
              align="center"
              prop="title"
              show-overflow-tooltip
              min-width="120"
            />
            <el-table-column
              label="类型"
              align="center"
              prop="name"
              show-overflow-tooltip
              min-width="120"
            >
              <template slot-scope="scope">
                <span :class="'type' + scope.row.type">{{
                  type_list[scope.row.type]
                }}</span>
              </template>
            </el-table-column>
            <el-table-column
              label="发放方式"
              align="center"
              prop="name"
              show-overflow-tooltip
              min-width="120"
            >
              <template slot-scope="scope">
                <span>{{ grant_type[scope.row.grant_type] }}</span>
              </template>
            </el-table-column>
            <el-table-column
              label="面值"
              align="center"
              prop="money"
              show-overflow-tooltip
              min-width="120"
            />
            <el-table-column
              label="有效期"
              align="center"
              prop="usefulTime"
              show-overflow-tooltip
              min-width="200"
            />
            <el-table-column
              label="活动叠加"
              align="center"
              prop="name"
              show-overflow-tooltip
              min-width="120"
            >
              <template slot-scope="scope">
                <span
                  :style="{
                    color: scope.row.activity_add == 1 ? '#f56c6c' : '#03a98e',
                  }"
                  >{{ activity_add_list[scope.row.activity_add] }}</span
                >
              </template></el-table-column
            >
            <el-table-column
              label="总数量"
              align="center"
              prop="num"
              show-overflow-tooltip
              min-width="120"
            >
              <template slot-scope="scope">
                {{ scope.row.grant_type == 3 ? "不限制" : scope.row.num }}
              </template>
            </el-table-column>
            <el-table-column
              label="可发放数量"
              align="center"
              prop="num"
              show-overflow-tooltip
              min-width="120"
            >
              <template slot-scope="scope">
                {{
                  scope.row.grant_type == 3
                    ? "不限制"
                    : scope.row.num - scope.row.grant_num
                }}
              </template></el-table-column
            >
            <el-table-column
              label="已领取数量"
              align="center"
              prop="grant_num"
              show-overflow-tooltip
              min-width="120"
            />
            <el-table-column
              label="状态"
              align="center"
              prop="name"
              show-overflow-tooltip
              min-width="120"
            >
              <template slot-scope="scope">
                <span :class="'status' + scope.row.status">
                  {{ status_list[scope.row.status] }}
                </span>
              </template></el-table-column
            >
            <el-table-column
              label="创建时间"
              align="center"
              prop="name"
              show-overflow-tooltip
              min-width="180"
            >
              <template slot-scope="scope">
                {{ parseTime(Number(scope.row.created_at)) }}
              </template>
            </el-table-column>
            <el-table-column
              label="管理操作"
              fixed="right"
              width="260"
              class-name="main_hei"
            >
              <template slot-scope="scope">
                <el-link
                  v-if="scope.row.status == 0 || scope.row.status == 1"
                  type="primary"
                  @click="handleGrant(scope.row)"
                  >发放</el-link
                >
                <router-link :to="'/marketing/coupon/record/' + scope.row.id">
                  <el-link type="primary">领取记录</el-link></router-link
                >
                <router-link :to="'/marketing/coupon/see/' + scope.row.id">
                  <el-link type="success">查看</el-link>
                </router-link>
                <el-dropdown
                  v-if="scope.row.status == 0 || scope.row.status == 1"
                >
                  <el-link type="primary">更多</el-link>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item
                      ><div>
                        <router-link
                          :to="'/marketing/coupon/edit/' + scope.row.id"
                          v-if="scope.row.status != 3 || scope.row.status != 1"
                        >
                          编辑</router-link
                        >
                      </div></el-dropdown-item
                    >
                    <el-dropdown-item
                      ><div @click="handleClose(scope.row)">
                        关闭
                      </div></el-dropdown-item
                    >
                  </el-dropdown-menu>
                </el-dropdown>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="main_page boxdq">
          <div></div>
          <!-- 分页 -->
          <div class="main_page_r">
            <el-pagination
              :current-page="current.page"
              :page-sizes="[20, 30, 50]"
              :page-size="limit"
              layout="total, sizes, prev, pager, next, jumper"
              :total="totalCount"
              background
              @size-change="(pageSize) => changeLimit(pageSize, 1)"
              @current-change="(page) => changePage(page, 1)"
            />
          </div>
        </div>
        <!-- 发放优惠券 -->
        <el-dialog
          title="优惠券发放"
          :visible.sync="grantDiaVisible"
          class="main_dialog dialog1000"
          @closed="closeDia"
        >
          <div class="mainor_form">
            <el-form
              :inline="true"
              :model="grant_form"
              class="demo-form-inline"
              ref="diaRefForm"
              label-width="70px"
              style="width: 100%"
            >
              <el-form-item label="" prop="uid">
                <change-user-input
                  class="wid220"
                  ref="changeUserInput"
                  @sendValue="
                    (data) => {
                      grant_form.uid = data.info.user_id;
                    }
                  "
                  @clear="grant_form.uid = ''"
                ></change-user-input>
              </el-form-item>
              <el-form-item label="" prop="group_id">
                <el-select
                  v-model.trim="grant_form.group_id"
                  placeholder="用户分组"
                  class="wid160"
                >
                  <el-option label="所有" :value="parseInt(0)"></el-option>
                  <el-option
                    v-for="(item, index) in group"
                    :key="index"
                    :label="item"
                    :value="parseInt(index)"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="" prop="region_id">
                <el-select
                  v-model.trim="grant_form.region_id"
                  placeholder="用户区域"
                  class="wid160"
                >
                  <el-option label="所有" :value="parseInt(0)"></el-option>
                  <el-option
                    v-for="(item, index) in region"
                    :key="index"
                    :label="item"
                    :value="parseInt(index)"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="" prop="salesman_id">
                <el-select
                  v-model.trim="grant_form.salesman_id"
                  placeholder="业务员"
                  class="wid160"
                >
                  <el-option label="所有" :value="parseInt(0)"></el-option>
                  <el-option
                    v-for="(item, index) in salesman"
                    :key="index"
                    :label="item"
                    :value="parseInt(index)"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button class="reset marginLeft10" @click="reset(2)"
                  >重置</el-button
                >
                <el-button
                  type="primary"
                  @click="getArticleList(2)"
                  :loading="dia_listLoading"
                  >搜索</el-button
                >
              </el-form-item>
            </el-form>
          </div>
          <div class="tips">
            剩余可发放数量：<em style="color: #e47c02">{{
              grant_info.reset_num
            }}</em>
          </div>
          <div class="main_table">
            <el-table
              ref="multipleTable"
              v-loading="dia_listLoading"
              :data="user_list"
              element-loading-text="加载中"
              fit
              border
              highlight-current-row
              :header-cell-class-name="this.$verticaline"
            >
              <el-table-column :render-header="renderheader" width="50">
                <template slot-scope="scope">
                  <el-checkbox
                    v-model="scope.row.checked"
                    @change="(val) => oneChange(val, scope.row)"
                  ></el-checkbox>
                </template>
              </el-table-column>
              <el-table-column
                label="用户名称"
                align="center"
                prop="nickname"
                show-overflow-tooltip
                min-width="120"
              />
              <el-table-column
                label="手机"
                align="center"
                prop="mobile"
                show-overflow-tooltip
                min-width="120"
              />
              <el-table-column
                label="已领取数量"
                align="center"
                prop="count"
                show-overflow-tooltip
                min-width="120"
              />
              <el-table-column
                label="最近一次领取时间"
                align="center"
                prop="get_time"
                show-overflow-tooltip
                min-width="180"
              >
              </el-table-column>
              <el-table-column
                label="发放数量"
                align="center"
                prop="name"
                show-overflow-tooltip
                min-width="120"
              >
                <template slot-scope="scope">
                  <el-input-number
                    v-model="scope.row.grant_num"
                    :min="1"
                    :precision="0"
                    :controls="false"
                  ></el-input-number>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <div class="main_page boxdq">
            <!-- 分页 -->
            <div></div>
            <div class="main_page_r">
              <el-pagination
                :current-page="grant_current.page"
                :page-sizes="[20, 50, 100]"
                :page-size="grant_limit"
                layout="total, sizes, prev, pager, next, jumper"
                :total="grant_totalCount"
                background
                @size-change="(pageSize) => changeLimit(pageSize, 2)"
                @current-change="(page) => changePage(page, 2)"
              />
            </div>
          </div>
          <div slot="footer">
            <span class="footer_tips"
              >本次发放数量共计：<em>{{ grant_sums }}</em></span
            >
            <el-button @click="grantDiaVisible = false">取 消</el-button>
            <el-button
              type="primary"
              :disabled="selectArr.length == 0 ? true : false"
              @click="batchGrant"
              v-repeatClick
              >批量发放</el-button
            >
          </div>
        </el-dialog>
      </div>
    </div>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import {
  get_coupons_index,
  get_coupons_close,
  get_grant_base,
  get_get_member,
  get_coupons_grant,
} from "@/api/marketing/marketing_coupon.js";
import { apiUrl, objKeySort, Md5 } from "@/utils/public";
import { parseTime } from "@/utils/index";
import { puzzleImg } from "@/api/currency";

export default {
  computed: {
    ...mapGetters(["avatar"]),
  },
  data() {
    return {
      // 时间
      parseTime,
      puzzleImg,
      // 分页
      current: {
        page: 1,
        per_page: 20,
      },
      limit: 20,
      totalCount: 1,
      // 列表数据
      list: [],
      status_list: [],
      type_list: {},
      activity_add_list: {},
      grant_type: {
        1: "后台发放",
        2: "用户领取",
        3: "新用户",
      },
      listLoading: false,
      // 搜索
      form: {
        type: null,
        status: null,
        title: "",
      },

      // 发放优惠券
      grantDiaVisible: false,
      grant_form: {
        uid: "",
        group_id: "",
        region_id: "",
        salesman_id: "",
      },

      user_list: [],
      grant_info: {},
      // 发放优惠券分页
      grant_current: {
        page: 1,
        per_page: 20,
      },
      // 全选
      selectArr: [],
      grant_limit: 20,
      grant_totalCount: 1,
      grant_sums: 0,
      dia_listLoading: false,
      grant_id: "",
      group: {},
      region: {},
      salesman: {},
      checkAll: false,
    };
  },
  watch: {
    user_list: {
      handler(val) {
        let all_list = val;
        let alllength = 0;
        let grant_num = 0;
        let arr = [];
        all_list.map((e) => {
          if (e.checked) {
            alllength++;
            grant_num += Number(e.grant_num);
            arr.push(e);
          }
        });
        this.grant_sums = grant_num;
        this.selectArr = arr;
        if (alllength == all_list.length) {
          this.checkAll = true;
        } else {
          this.checkAll = false;
        }
      },
      deep: true,
    },
  },
  created() {
    // 列表
    this.get_coupons_index();
    this.get_grant_base();
  },

  methods: {
    // 搜索
    getArticleList(type) {
      switch (type) {
        case 1:
          this.current.page = 1;
          this.get_coupons_index();
          break;
        case 2:
          this.grant_current.page = 1;
          this.get_get_member();
          break;
      }
    },
    // 重置
    reset(type) {
      switch (type) {
        case 1:
          this.$refs["userListFrom"].resetFields();
          this.get_coupons_index();
          break;
        case 2:
          this.$refs["diaRefForm"].resetFields();
          if (this.$refs["changeUserInput"]) {
            this.$refs["changeUserInput"].name = "";
          }
          this.get_get_member();
          break;
      }
    },
    // 更多
    more() {
      this.moredata = !this.moredata;
    },
    // 分页
    changeLimit(pageSize, type) {
      switch (type) {
        case 1:
          this.current.per_page = pageSize;
          this.get_coupons_index();
          break;
        case 2:
          this.grant_current.per_page = pageSize;
          this.get_get_member();
          break;
      }
    },
    changePage(page, type) {
      switch (type) {
        case 1:
          this.current.page = page;
          this.get_coupons_index();
          break;
        case 2:
          this.grant_current.page = page;
          this.get_get_member();
          break;
      }
    },
    // 列表
    get_coupons_index() {
      this.listLoading = true;
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(
              Object.assign(apiUrl().name, this.list_form(), this.current)
            ) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        this.list_form(),
        this.current
      );
      get_coupons_index(data).then((res) => {
        this.listLoading = false;
        if (res.errcode == 0) {
          res.data.list.data.map((e) => {
            let time = [];
            e.usefulTime = "";
            if (e.expire_type == 1) {
              time = [
                this.parseTime(e.start_time, "{y}-{m}-{d}"),
                this.parseTime(e.end_time, "{y}-{m}-{d}"),
              ];
              e.usefulTime = time.join(" 至 ");
            } else if (e.expire_type == 2) {
              // let start_time = Number(e.created_at);
              // let end_time = new Date(start_time * 1000);
              // end_time.setDate(end_time.getDate() + e.expire_days);
              // start_time = this.parseTime(start_time, "{y}-{m}-{d}");
              // end_time = this.parseTime(end_time, "{y}-{m}-{d}");
              // time = [start_time, end_time];
              e.usefulTime = "发放起 " + e.expire_days + " 天内";
            }
          });
          this.list = res.data.list.data;
          this.totalCount = res.data.list.total;
          this.activity_add_list = res.data.activity_add_list;
          this.status_list = res.data.status_list;
          this.type_list = res.data.type_list;
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
    list_form() {
      let form = JSON.parse(JSON.stringify(this.form));
      return form;
    },
    renderheader(h, { column, $index }) {
      return h("el-checkbox", {
        // 表示属性
        attrs: {
          effect: "dark",
        },
        props: {
          value: this.checkAll,
        },
        on: {
          change: (val) => {
            this.changeAll(val);
          },
        },
      });
    },
    // 选择全部
    changeAll(val) {
      this.checkAll = val;
      // 全选反选
      this.user_list.map((e) => {
        e.checked = val;
      });
    },
    // 一级选择
    oneChange(val, row) {
      row.checked = val;
    },
    // 关闭
    handleClose(row) {
      let id = row.id;
      this.$confirm(
        "活动关闭后无法恢复, 已参与活动的订单不受影响，确认关闭?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          let data = Object.assign(
            {
              sign: Md5(
                objKeySort(
                  Object.assign(apiUrl().name, this.list_form(), this.current)
                ) + apiUrl().appsecret
              ),
            },
            apiUrl().name,
            {
              id: id,
            }
          );
          get_coupons_close(data).then((res) => {
            if (res.errcode == 0) {
              this.$message.success("关闭成功");
              this.get_coupons_index();
            } else {
              this.$message.error(res.errmsg);
            }
          });
        })
        .catch(() => {});
    },
    // 获取发放信息
    get_grant_base() {
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
          ),
        },
        apiUrl().name
      );
      get_grant_base(data).then((res) => {
        if (res.errcode == 0) {
          this.group = res.data.group;
          this.region = res.data.region;
          this.salesman = res.data.salesman;
        }
      });
    },
    get_get_member() {
      this.dia_listLoading = true;
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(
              Object.assign(apiUrl().name, this.grant_form, this.grant_current)
            ) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        this.grant_current,
        this.grant_form,
        { id: this.grant_id }
      );
      get_get_member(data).then((res) => {
        if (res.errcode == 0) {
          res.data.info.reset_num = 0;
          if (res.data.info.grant_type == 3) {
            res.data.info.reset_num = "不限制";
          } else {
            let num =
              parseFloat(res.data.info.num) -
              parseFloat(res.data.info.grant_num);
            res.data.info.reset_num = num;
          }
          this.grant_info = res.data.info;
          res.data.list.map((e) => {
            e.grant_num = 1;
            e.checked = false;
          });
          this.user_list = res.data.list;
          this.grant_totalCount = res.data.total;
          this.dia_listLoading = false;
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
    // 关闭弹窗
    closeDia() {
      this.grant_form.uid = "";
      this.grant_form.group_id = "";
      this.grant_form.region_id = "";
      this.grant_form.salesman_id = "";
      this.grant_current.page = 1;
      this.grant_current.per_page = 20;
      this.grant_limit = 20;
      this.grant_totalCount = 1;
      this.grant_sums = 0;
      this.grant_id = "";
      this.user_list = [];
      this.grant_info = {};
    }, // 发放
    handleGrant(row) {
      let id = row.id;
      this.grant_id = id;
      this.get_get_member();
      this.grantDiaVisible = true;
    },

    // 批量发放
    batchGrant() {
      let selectArr = JSON.parse(JSON.stringify(this.selectArr));
      let sums = 0;
      let list = selectArr.map((e) => {
        sums += Number(e.grant_num);
        let { checked, count, get_time, mobile, nickname, ...sz } = e;
        return { ...sz };
      });
      if (this.grant_info.grant_type != 3) {
        if (sums > this.grant_info.reset_num) {
          this.$message.error("当前发放数量超出剩余优惠券数量");
          return;
        }
      }
      let id = this.grant_info.id;

      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        {
          id: id,
          list: JSON.stringify(list),
        }
      );

      get_coupons_grant(data).then((res) => {
        if (res.errcode == 0) {
          this.$message.success("发放成功");
          this.grantDiaVisible = false;
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
  },
};
</script>
<style lang="scss" scoped>
@import "@/styles/variables.scss";

.mainsu {
  .mainor_form form {
    width: calc(100% - 120px);
  }
  .main_num {
    .mainsu_te {
      position: relative;
      top: -1px;
    }
  }
}
/deep/.el-progress-bar__innerText {
  transform: translateY(-1px);
}
.main_dialog {
  .main_table {
    /deep/.el-table__body-wrapper {
      overflow-y: auto;
      height: 400px;
    }
  }
  .main_xq ul li {
    width: 33.33%;
    margin-top: 5px;
    margin-bottom: 5px;
  }
  .progress_list {
    margin-top: 10px;
    p {
      height: 24px;
      line-height: 24px;
    }
    .progress_list_red {
      color: red;
    }
    .progress_list_su {
      color: #03a98e;
    }
  }
}

.type1 {
  color: #03a98e;
}
.type2 {
  color: #aacd6e;
}

.status0 {
  color: #aacd6e;
}
.status1 {
  color: #03a98e;
}
.status2 {
  color: #f56c6c;
}
.status3 {
  color: #cccccc;
}
/deep/ .main_table .el-table--small td .cell {
  height: auto;
  white-space: normal !important;
  p {
    margin: 0 5px;
    background-color: #f0f9eb;
    color: #67c23a;
    padding: 2px 0;
  }
  .goods_data_span {
    background-color: #fef0f0;
    color: #f56c6c;
    padding: 2px;
    margin-right: 2px;
    margin-bottom: 5px;
    display: inline-block;
  }
}
.main_dialog /deep/ .el-checkbox {
  margin-bottom: 0;
}
.footer_tips {
  padding-right: 25px;
  color: #606266;
  em {
    color: red;
  }
}
</style>
